from rest_framework import serializers
from .models import UserData, models  # 注意这里添加了 models 导入
from django.contrib.auth.hashers import make_password
from django.contrib.auth.hashers import check_password, make_password
from rest_framework import serializers
from .models import UserData,Shop
from django.db.utils import IntegrityError
class ShopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Shop
        fields = ['id', 'name', 'shop_type', 'is_cross_border', 'province', 'invite_code', 'created_at']
        read_only_fields = ['id', 'created_at']

class UserDataSerializer(serializers.ModelSerializer):
    shop_name = serializers.CharField(write_only=True)
    invite_code = serializers.CharField(required=False, allow_blank=True, write_only=True)
    province = serializers.CharField(required=False, allow_blank=True)  # 添加省份字段

    class Meta:
        model = UserData
        fields = ['id', 'username', 'password', 'email', 'phone', 'province',
                  'shop_name', 'invite_code', 'created_at', 'updated_at']
        extra_kwargs = {
            'password': {'write_only': True},
            'created_at': {'read_only': True},
            'updated_at': {'read_only': True},
        }

    def create(self, validated_data):
        shop_name = validated_data.pop('shop_name')
        invite_code = validated_data.pop('invite_code', '')
        province = validated_data.pop('province', '')  # 获取省份数据

        # 查找或创建店铺
        try:
            shop = Shop.objects.get(name=shop_name)
            # 验证邀请码
            if shop.invite_code and not check_password(invite_code, shop.invite_code): raise serializers.ValidationError(
                {"invite_code": "邀请码无效"})
        except Shop.DoesNotExist:
            # 创建新店铺
            shop = Shop.objects.create(
                name=shop_name,
                shop_type=self.context.get('shop_type', 'normal'),
                is_cross_border=self.context.get('is_cross_border', False),
                invite_code=invite_code if invite_code else None
            )

        # 创建用户并关联到店铺
        validated_data['shop'] = shop
        validated_data['password'] = make_password(validated_data['password'])
        # 将省份设置到用户而不是店铺
        validated_data['province'] = province

        try:
            return super().create(validated_data)
        except IntegrityError as e:
            # 处理唯一约束错误
            if 'username' in str(e):
                raise serializers.ValidationError({"username": "该用户名已注册"})
            elif 'email' in str(e):
                raise serializers.ValidationError({"email": "该邮箱已注册"})
            elif 'phone' in str(e):
                raise serializers.ValidationError({"phone": "该电话号码已注册"})
            else:
                raise serializers.ValidationError("注册失败，请联系管理员")


from rest_framework import serializers
from .models import Product, InventoryOperation

# 必须保留 ProductSerializer
class ProductSerializer(serializers.ModelSerializer):
    username = serializers.CharField(write_only=True, required=False)
    shop_name = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Product
        fields = ['id', 'name', 'code', 'spec', 'cost', 'price', 'stock', 'shop', 'username', 'shop_name', 'created_at',
                  'updated_at']
        read_only_fields = ('id', 'created_at', 'updated_at')
        extra_kwargs = {
            'shop': {'required': False}
        }

    def create(self, validated_data):
        username = validated_data.pop('username', None)
        shop_name = validated_data.pop('shop_name', None)

        if username:
            # 根据用户名找到用户和关联的店铺
            try:
                user = UserData.objects.get(username=username)
                validated_data['shop'] = user.shop
            except UserData.DoesNotExist:
                raise serializers.ValidationError({"username": "用户不存在"})
        elif shop_name:
            # 直接根据店铺名找到店铺
            try:
                shop = Shop.objects.get(name=shop_name)
                validated_data['shop'] = shop
            except Shop.DoesNotExist:
                raise serializers.ValidationError({"shop_name": "店铺不存在"})

        return super().create(validated_data)


class OperationSerializer(serializers.ModelSerializer):
    timestamp = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S.%fZ", read_only=True)
    operation_type_display = serializers.CharField(source='get_operation_type_display', read_only=True)
    product_code = serializers.CharField(source='product.code', read_only=True)
    write_product_code = serializers.CharField(write_only=True)
    username = serializers.CharField(write_only=True, required=False)  # 添加操作人字段

    class Meta:
        model = InventoryOperation
        fields = [
            'id',
            'operation_type',
            'operation_type_display',
            'quantity',
            'note',
            'operator',
            'timestamp',
            'product_code',
            'write_product_code',
            'username'
        ]
        extra_kwargs = {
            'product': {'write_only': True},
            'operation_type': {'write_only': True}
        }

    def create(self, validated_data):
        write_product_code = validated_data.pop('write_product_code', None)
        username = validated_data.pop('username', None)

        # 保存操作人
        if username:
            validated_data['operator'] = username

        # 这里不创建实例，而是在视图中处理
        return validated_data


from rest_framework import serializers
from .models import NormalOrder, PrivateOrder


class NormalOrderSerializer(serializers.ModelSerializer):
    username = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = NormalOrder
        fields = ['id', 'order_id', 'customer', 'product', 'quantity', 'amount', 'created_at', 'shop', 'creator',
                  'username']
        read_only_fields = ['id', 'created_at']
        extra_kwargs = {
            'shop': {'required': False},
            'creator': {'required': False}
        }

    def create(self, validated_data):
        username = validated_data.pop('username', None)

        if username:
            try:
                user = UserData.objects.get(username=username)
                validated_data['shop'] = user.shop
                validated_data['creator'] = user
            except UserData.DoesNotExist:
                raise serializers.ValidationError({"username": "用户不存在"})

        return super().create(validated_data)


class PrivateOrderSerializer(serializers.ModelSerializer):
    username = serializers.CharField(write_only=True, required=False)
    qkd_key = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = PrivateOrder
        fields = ['id', 'order_id', 'customer', 'product', 'quantity', 'amount', 'created_at', 'shop', 'creator',
                  'username', 'qkd_key']
        read_only_fields = ['id', 'created_at']
        extra_kwargs = {
            'shop': {'required': False},
            'creator': {'required': False}
        }

    def create(self, validated_data):
        username = validated_data.pop('username', None)
        qkd_key = validated_data.pop('qkd_key', None)

        if not qkd_key:
            raise serializers.ValidationError({"qkd_key": "必须提供QKD密钥"})

        if username:
            try:
                user = UserData.objects.get(username=username)
                validated_data['shop'] = user.shop
                validated_data['creator'] = user
            except UserData.DoesNotExist:
                raise serializers.ValidationError({"username": "用户不存在"})

        return super().create(validated_data)

